package tools

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"path/filepath"
	"peilian-api/app/global/log"
	"strings"
	"sync"
	"time"

	"github.com/gin-gonic/gin"
)

func NewJsonRequest(method, url string, j interface{}) (*http.Request, error) {
	data, err := json.Marshal(j)
	if err != nil {
		return nil, err
	}
	req, err := http.NewRequest(method, url, bytes.NewReader(data))
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json")
	return req, nil
}

func DefaultHttpDoJson(method, url string, jsonData interface{}, headerPairs ...string) (*http.Response, error) {
	req, err := NewJsonRequest(method, url, jsonData)
	if err != nil {
		return nil, err
	}

	for i := 0; i < len(headerPairs)-1; i += 2 {
		key := headerPairs[i]
		val := headerPairs[i+1]
		req.Header.Set(key, val)
	}

	client := HttpClient(10 * time.Second)
	defer HttpClientPool.Put(client)

	return client.Do(req)
}

var HttpClientPool = sync.Pool{
	New: func() interface{} {
		return &http.Client{}
	},
}

func HttpClient(timeout time.Duration) *http.Client {
	client, ok := HttpClientPool.Get().(*http.Client)
	if !ok {
		client = &http.Client{}
	}
	client.Timeout = timeout
	return client
}

func ReadResponseBody(resp *http.Response, data interface{}) error {
	if resp == nil || resp.Body == nil {
		return fmt.Errorf("empty response")
	}

	body, err := io.ReadAll(resp.Body)
	defer resp.Body.Close()

	if err != nil {
		return err
	}
	log.ZapLogger.Info("接口返回数据：" + string(body))

	return json.Unmarshal(body, data)
}

func ReadResponseBodyCtx(ctx *gin.Context, resp *http.Response, data interface{}) error {
	if resp == nil || resp.Body == nil {
		return fmt.Errorf("empty response")
	}

	body, err := io.ReadAll(resp.Body)
	defer resp.Body.Close()

	if err != nil {
		return err
	}
	log.Logger.InfoF(ctx, "接口返回数据："+string(body))

	return json.Unmarshal(body, data)
}

func ReadResponseBodyWithRaw(resp *http.Response, data interface{}) (int, string, error) {
	if resp == nil || resp.Body == nil {
		return 0, "", fmt.Errorf("empty response")
	}

	body, err := ioutil.ReadAll(resp.Body)
	defer resp.Body.Close()

	if err != nil {
		return resp.StatusCode, "", err
	}

	if data != nil {
		err = json.Unmarshal(body, data)
	}

	return resp.StatusCode, string(body), err
}

func ServeFile(c *gin.Context, fullfile string) {
	arr := strings.Split(fullfile, ".")
	paths := strings.Split(fullfile, string(filepath.Separator))
	filename := paths[len(paths)-1]
	switch arr[len(arr)-1] {
	case "xlsx":
		c.Writer.Header().Set("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
		c.Writer.Header().Set("Content-Disposition", "attachment; filename=\""+filename+"\"")
	}
	http.ServeFile(c.Writer, c.Request, fullfile)
}
